from django.shortcuts import render_to_response
from datetime import datetime
from django.http import HttpResponseRedirect
from trafficlight.gossips.models import Message 
from trafficlight.gossips.forms import MessageForm
# Create your views here.

def index(request):
	# implementation of a list of messages
	messages = Message.objects.order_by('-post_time')[0:10]
	if not messages :
		return render_to_response('gossips/index.html')
	return render_to_response('gossips/index.html', { 'messages' : messages })

def leave_message(request):
	# implementation of leaving message
	if request.method == 'POST' :
		form = MessageForm(request.POST)
		if form.is_valid() :
			cd = form.cleaned_data
			name = cd['name']
			post_time = datetime.now() 
			text = cd['text']
			title = cd['title']
			email = cd['email']
			message = Message(text=text,
				title=title,
				post_time=post_time,
				name=name,
				email=email)
			message.save()
			return HttpResponseRedirect('/gossip/')
		else:
			return render_to_response('gossips/leave_message.html',
				{ 'form' : form })
	else:
		form = MessageForm()
		return render_to_response('gossips/leave_message.html',
				{ 'form' : form })
